package com.yike.product.controller.feign;

import com.yike.common.base.BaseController;
import com.yike.common.exception.BusinessException;
import com.yike.product.api.vo.GoodsFeignVo;
import com.yike.product.mapper.GoodsMapper;
import com.yike.user.api.service.ShopFeignService;
import com.yike.user.api.vo.ShopFeignVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Set;

/**
 * 权限表 控制器
 *
 * @author yike
 * @since 2023-08-24
 */
@RestController
@RequestMapping("/feign/goods")
@ApiIgnore // 暂时不显示到文档
public class GoodsFeignController extends BaseController {

    @Autowired
    private GoodsMapper goodsMapper;
    @Resource
    private ShopFeignService shopFeignService;

    @GetMapping("/list")
    public List<GoodsFeignVo> list(@RequestParam("goodsIds") Set<Long> goodsIds) {
        List<GoodsFeignVo> goodsFeignVos = goodsMapper.getGoodsListByIds(goodsIds);
        for (GoodsFeignVo goodsFeignVo : goodsFeignVos) {
            // 客户端扫码的时候需要判断当前店铺是否开启了一键调价
            ShopFeignVo shopFeignVo = shopFeignService.getShop(goodsFeignVo.getShopId());
            if (shopFeignVo == null) {
                throw new BusinessException("店铺信息异常，请联系工作人员");
            }
            // 如果开启了调价那么当前所有商品价格都需要上涨
            if (shopFeignVo.getAdjustPriceFlag()) {
                // 将调价百分比转为 1.xx 格式，比如 10% 就是 1.10
                BigDecimal adjustmentFactor = BigDecimal.valueOf(1).add(BigDecimal.valueOf(shopFeignVo.getAdjustPriceRate()).divide(BigDecimal.valueOf(100)));
                // 计算调价后的新价格，并保留两位小数
                BigDecimal adjustedPrice = goodsFeignVo.getSellPrice().multiply(adjustmentFactor).setScale(2, RoundingMode.HALF_UP);
                // 设置新的价格
                goodsFeignVo.setSellPrice(adjustedPrice);
            }
        }
        return goodsFeignVos;
    }

}

